import { useI18n } from 'vue-i18n'
// 全局请求封装
// const base_url = 'http://192.168.0.98:9998'
// const base_url = 'http://192.168.0.98:8889'
// const base_url = 'http://192.168.0.223:8080' // 旧地址
const base_url = 'http://192.168.0.98:9998' // 新地址
// const base_url = process.env.NODE_ENV === 'development' ? '/api' : 'http://192.168.0.98:9998/'  // 生产环境用域名，开发环境用代理
// 请求超出时间
const timeout = 60000

// 登录接口路径（根据实际项目修改）
const LOGIN_URLS = [
	'/dpl/v1/auth/login/phone',
	'/dpl/v1/auth/login/email',
	'/dpl/v1/auth/register', // 可选：注册接口也不需要token
	'/dpl/v1/auth/refresh' // 可选：刷新token接口
]
// 防抖函数
const debounce = (fn, delay) => {
	let timer = null;
	return function (...args) {
		if (timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	};
};
const outLogin = () => {
	// uni.showModal({ // 登录过期处理
	// 	title: useI18n.global.t('prompt'),
	// 	content: useI18n.global.t('pleaselogin'),
	// 	showCancel: false,
	// 	success() {
	// 		setTimeout(() => {
	// 			// 关闭所有页面，打开/pages/login/login
	// 			uni.reLaunch({
	// 				url: "/pages/login/login",
	// 			})
	// 		}, 1000);
	// 	},
	// });
	setTimeout(() => {
		// 关闭所有页面，打开/pages/login/login
		uni.reLaunch({
			url: "/pages/login/login",
		})
	}, 1000);
	uni.setStorageSync('token', '')
	uni.setStorageSync('refreshToken', '')
	uni.setStorageSync('accessTokenExp', '')
	uni.setStorageSync('avatarUrl', '')
	uni.setStorageSync('username', '')
	uni.setStorageSync('userCode', '')
	uni.setStorageSync('dplID', '')
	uni.setStorageSync('userPhone', '')
}
const debouncedOutLogin = debounce(outLogin, 500);
// 需要修改token，和根据实际修改请求头
const request = (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};

	// 判断是否为登录请求
	const isLoginRequest = LOGIN_URLS.some(loginUrl => url.startsWith(loginUrl))

	// 只有非登录请求才添加 token
	let header = {
		'Content-Type': 'application/json;charset=UTF-8',
		...params.header
	}

	// 非登录请求添加 token  || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDc4MTQ1ODksInRva2VuIjoiMTA3MiJ9.TPPIuyBYSXa96zyC5rjz4bbd1jos88C-0AQWHKLkIa4'
	// console.log("储存中获取token", uni.getStorageSync('token'))
	if (!isLoginRequest) {
		header['Authorization'] = uni.getStorageSync('token')
	}
	// if (method == "post") {
	// 	header = {
	// 		'Content-Type': 'multipart/form-data' // 自定义，跟后台约定好传什么格式的
	// 	};
	// }
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
			timeout: timeout,
			success(response) {
				const res = response
				if (!res.data.code) return
				if (res.data.code == 997) {
					try {
						let refreshToken = uni.getStorageSync('refreshToken')
						if (refreshToken) {// 刷新token
							uni.request({
								url: base_url + '/dpl/v2/auth/refreshToken',
								method: 'POST',
								header: header,
								data: { refreshToken: refreshToken },
								timeout: 10000
							}).then(res => {
								if (res.data.code == 200) {
									uni.setStorageSync('token', res.data.tokenList.accessToken)
									uni.request({// 重新请求
										url: base_url + url,
										method: method,
										header: {
											'Content-Type': 'application/json;charset=UTF-8',
											'Authorization': res.data.tokenList.accessToken
										},
										data: data,
										timeout: timeout,
										success: (retryRes) => resolve(retryRes.data),
										fail: (retryErr) => reject(retryErr)
									});
								} else {
									debouncedOutLogin()
								}
							}).catch(err => {
								debouncedOutLogin()
							})
						} else {
							debouncedOutLogin()
						}
					} catch (e) {
						debouncedOutLogin()
					}
				}

				// 根据返回的状态码做出对应的操作
				//获取成功
				// console.log(res.statusCode);
				if (res.statusCode == 200) {
					resolve(res.data);
				} else {
					uni.clearStorageSync()
					switch (res.statusCode) {
						case 401:
							uni.showModal({ // 登录过期处理
								title: useI18n.global.t('prompt'),
								content: useI18n.global.t('pleaselogin'),
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.reLaunch({
											url: "/pages/login/login",
										})
									}, 1000);
								},
							});
							break;
						case 404:
							uni.showToast({
								title: useI18n.global.t('Therequestaddressdoesnotexist'),
								icon: 'none',
								duration: 2000
							})
							break;
						case 500: // 添加500状态码处理
							uni.showToast({
								title: useI18n.global.t('Anerrorpleasetryagain'),
								icon: 'none',
								duration: 2000
							});
							console.error('服务器错误详情:', res.data); // 打印错误详情用于调试
							break;
						default:
							uni.showToast({
								title: useI18n.global.t('Anerrorpleasetryagain'),
								icon: 'none',
								duration: 2000
							})
							break;
					}
				}
			},
			fail(err) {
				console.log(err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					uni.showToast({
						title: useI18n.global.t('networkanomaly'),
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: useI18n.global.t('Anerrorpleasetryagain'),
						duration: 2000
					})
				}
				reject(err);

			},
			complete() {
				// 不管成功还是失败都会执行
				uni.hideLoading();
				uni.hideToast();
			}
		});
	}).catch(() => { });
};

export default request;